package com.tg.app.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.RecyclerView;

import com.demo.view.BottomFullDialog;
import com.demo.view.TGBottomFullDialog;
import com.tg.app.R;
import com.tg.app.activity.device.CameraViewActivity;
import com.tg.app.adapter.PrePositionAdapter;
import com.tg.app.adapter.PrePositionFragmentAdapter;
import com.tg.app.bean.DevicePresetPoints;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.Camera;
import com.tg.app.camera.CameraHelper;
import com.tg.app.util.ObjectBoxUtil;
import com.tg.app.view.wheelview.WheelView;
import com.tange.base.toolkit.DimenUtil;
import com.tg.appcommon.android.ImageUtils;
import com.tg.appcommon.android.LanguageUtils;
import com.tg.appcommon.android.Packet;
import com.tange.base.toolkit.StringUtils;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tange.base.toolkit.TGThreadPool;
import com.tg.appcommon.android.TGToast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * Describe:
 * Created by Rance Rang on 2019-12-21.
 * <p>
 * Copyright (c) Tange.Inc All rights reserved.
 */
public class PrePositionControlView extends LinearLayout implements PrePositionAdapter.PrePositionListener{
    private static final String TAG = PrePositionControlView.class.getSimpleName();
    private PrePositionAdapter adapter;
    protected AVIOCTRLDEFs.Tcis_SetPtzPosReq ptzPos;
    protected Camera camera;
    protected Context context;
    private Bitmap bitmap;
    protected short pspType;
    private TextView delImage, guardImage, ptzReset;
    private TextView delCancel, delSubmit;
    private BottomFullDialog bottomFullDialog;
    protected boolean isSupportWatchPos = false;
    protected int curSelectIdleTime = -1;
    private View mView;

    public void setSupportPTZReset(boolean supportPTZReset) {
        isSupportPTZReset = supportPTZReset;
        setPTZResetShow(isSupportPTZReset);
    }

    private void setPTZResetShow(boolean show){
        ptzReset.setVisibility(show? VISIBLE : GONE);
        if (mView != null){
            mView.setVisibility(show? VISIBLE : GONE);
        }
    }

    private boolean isSupportPTZReset = false;
    public void setSupportWatchPos(boolean supportWatchPos) {
        isSupportWatchPos = supportWatchPos;
        showGuardImageButton();
    }
    private void showGuardImageButton(){
        if (guardImage != null){
            guardImage.setVisibility(isSupportWatchPos? VISIBLE : GONE);
        }
    }


    private void showDialog(View outerView) {
        //防止弹出两个窗口
        if (bottomFullDialog !=null && bottomFullDialog.isShowing()) {
            return;
        }

        bottomFullDialog = new TGBottomFullDialog(getContext(), outerView);
        bottomFullDialog.setCancelable(true);
        bottomFullDialog.setOnTouchDismiss(false);
        bottomFullDialog.setCanceledOnTouchOutside(true);
        bottomFullDialog.show();
    }

    private void dismissDialog() {
        if (bottomFullDialog != null) {
            bottomFullDialog.dismiss();
        }
    }

    private void setWheelDate(WheelView wheelView, final boolean isNewPosition, int curTime) {
        String[] guards = TGApplicationBase.getResources().getStringArray(R.array.guard);
        List<String> list = new ArrayList<>(Arrays.asList(guards));
        if (isNewPosition){
            list.remove(list.size() - 1);
        }
        int pos;
        for (pos = 0; pos < list.size(); ++pos){
            if (!StringUtils.isEmpty(list.get(pos)) && list.get(pos).contains(Integer.toString(curTime))){
                break;
            }
        }
        if (pos < list.size()){
            wheelView.setItems(list, pos);
            //联动逻辑效果
            wheelView.setOnItemSelectedListener((index, item) -> {
                TGLog.d(TAG, "index = " + index + ", item = " + item);
                if (isNewPosition){
                    if (index < list.size()){
                        curSelectIdleTime = index * 10 + 10;
                    }
                }else{
                    if (index < list.size() - 1){
                        curSelectIdleTime = index * 10 + 10;
                    }else if (index == list.size() - 1){
                        curSelectIdleTime = 0;
                    }
                }
            });
        }

    }

    private void showGuardDialog() {
        @SuppressLint("InflateParams") View outerView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pre_guard_position, null);
        final WheelView wheelGuard =  outerView.findViewById(R.id.dialog_guard);
        final DevicePresetPoints devicePresetPoints = adapter.getDevicePresetPoints(adapter.getSelectPosition());
        final boolean isNewPosition = devicePresetPoints == null || devicePresetPoints.num != adapter.getWatchPosNumber();
        if (isNewPosition){
            wheelGuard.setTextColorLast(wheelGuard.getTextColorCenter());
        }
        curSelectIdleTime = adapter.getIdleTime();
        setWheelDate(wheelGuard, isNewPosition, adapter.getIdleTime());
        outerView.findViewById(R.id.dialog_week_time_cancle).setOnClickListener(v ->{
            curSelectIdleTime = -1;
            dismissDialog();
        });
        outerView.findViewById(R.id.dialog_week_time_submit).setOnClickListener(v -> {
            if (isSupportWatchPos && curSelectIdleTime != -1){
                int num = -1;
                if (curSelectIdleTime != 0 && devicePresetPoints != null){
                    TGLog.d(TAG, "num = " + devicePresetPoints.num + ", idleTime = " + curSelectIdleTime);
                    num = devicePresetPoints.num;
                }
                CameraHelper.settWatchPosCMD(camera, 0, num, curSelectIdleTime);
            }
            dismissDialog();
        });
        showDialog(outerView);
    }

    public PrePositionControlView(Context context) {
        super(context);
        initView(context);
    }

    public PrePositionControlView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }


    public PrePositionControlView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    public void setPtzPos(AVIOCTRLDEFs.Tcis_SetPtzPosReq ptzPos) {
        this.ptzPos = ptzPos;
    }


    public void receiveIOCtrlData(int type, @NonNull byte[] data) {
        TGLog.d(TAG,"type = " + type);
        if (type == AVIOCTRLDEFs.TCI_CMD_GET_PSP_RESP) {
            pspType = CameraHelper.getPresetPointsTypeResp(data);
            if (isSupportWatchPos){
                CameraHelper.getWatchPosCMD(camera);
            }

            TGThreadPool.executeOnUiThread(() -> getPresetPointsResp(data));
        } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_WATCHPOS_RESP){
            int num = Packet.byteArrayToInt_Little(data, 4);
            int times = Packet.byteArrayToInt_Little(data, 8);
            TGLog.d(TAG,"num = " + num + ", times = " +  ", adapter.isExistDevicePresetPoints(num) = " + adapter.isExistDevicePresetPoints(num));
            if (num != -1 && adapter.isExistDevicePresetPoints(num)){
                curSelectIdleTime = times;
                adapter.setWatchPosInfo(num, times);
            }

        } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_PTZ_POS_RESP) {
            ptzPos = CameraHelper.getPtzPosResp(data);

        } else if (type == AVIOCTRLDEFs.TCI_CMD_SET_COMMAND_RESP) {
            int command = CameraHelper.getSetCommand(data);
            int result = CameraHelper.getSetCommandResult(data);
            if (command == AVIOCTRLDEFs.TCI_CMD_SET_PSP || command == AVIOCTRLDEFs.TCI_CMD_SET_WATCHPOS_REQ) {
                TGToast.showToast(result == 0 ? R.string.camera_send_completed : R.string.camera_send_failed);
                if (command == AVIOCTRLDEFs.TCI_CMD_SET_PSP){
                    TGThreadPool.executeOnUiThread(() -> {
                        int num = adapter.getWatchPosNumber();
                        delResp(result);
                        if (num != -1 && !adapter.isExistDevicePresetPoints(num)){
                            CameraHelper.settWatchPosCMD(camera, 0, -1, 0);
                        }
                        TGLog.d(TAG,"num = " + num + ", times = " +  ", isExistDevicePresetPoints(num) = " + adapter.isExistDevicePresetPoints(num));
                    });

                }else {
                    TGLog.d(TAG, "adapter.getWatchPosNumber() = " + adapter.getWatchPosNumber());
                    if (isSupportWatchPos){
                        DevicePresetPoints devicePresetPoints = adapter.getDevicePresetPoints(adapter.getSelectPosition());
                        int num = -1;
                        if (curSelectIdleTime != 0 && devicePresetPoints != null){
                            TGLog.d(TAG, "num = " + devicePresetPoints.num + ", idleTime = " + curSelectIdleTime);
                            num = devicePresetPoints.num;
                        }
                        adapter.setWatchPosInfo(num, curSelectIdleTime);
                        CameraHelper.getWatchPosCMD(camera);
                    }
                }
            }
        }
    }

    public void init(){
        delCancel.setVisibility(View.GONE);
        delSubmit.setVisibility(View.GONE);
        delImage.setVisibility(View.VISIBLE);
        showGuardImageButton();
        adapter.clearSelectedPresetPoints();
        adapter.setEditEnable(false);
    }

    private void delResp(int result) {
        if (result == 0 && adapter.isEditEnable()) {
            delCancel.setVisibility(View.GONE);
            delSubmit.setVisibility(View.GONE);
            delImage.setVisibility(View.VISIBLE);
            setPTZResetShow(isSupportPTZReset);
            showGuardImageButton();
            adapter.clearPointFromSelected();
            adapter.setEditEnable(false);
        }
    }

    private void getPresetPointsResp(byte[] data) {
        List<DevicePresetPoints> list = CameraHelper.getPresetPointsResp(data,false );
        TGLog.d(TAG,"size =" + list.size());
        for (DevicePresetPoints l:list){
            l.uuid = camera != null? camera.uid : l.uuid;
            TGLog.d(TAG,"num =" +l.num);
        }
        adapter.setData(list);
        if (camera != null){
            ObjectBoxUtil.saveDevicePresetPoints(list, camera.uid);
        }

        adapter.setEditEnable(false);
        if (adapter.getPrePositions().size() == 0) {
            setDelCancel();
        } else {
            delImage.setVisibility(View.VISIBLE);
            setPTZResetShow(isSupportPTZReset);
            showGuardImageButton();
        }
    }

    private void setDelCancel() {
        delCancel.setVisibility(View.GONE);
        delSubmit.setVisibility(GONE);
        adapter.setEditEnable(false);
    }


    public void initView(Context context) {
        this.context = context;
        @SuppressLint("InflateParams") View view = LayoutInflater.from(context).inflate(R.layout.layout_pre_position_ctl, null);
        addView(view);
        delImage = view.findViewById(R.id.bottom_sheet_pre_position_del_btn);
        guardImage = view.findViewById(R.id.bottom_sheet_pre_position_guard_btn);
        ptzReset = view.findViewById(R.id.bottom_sheet_pre_position_reset_btn);
        delCancel = view.findViewById(R.id.bottom_sheet_pre_position_del_cancel);
        delSubmit = view.findViewById(R.id.bottom_sheet_pre_position_del_submit);
        mView = view.findViewById(R.id.view2);
        PrePositionDialog.RecyclerViewGridLayoutManager gridLayoutManager = new PrePositionDialog.RecyclerViewGridLayoutManager(context, 3);
        RecyclerView recyclerView = view.findViewById(R.id.pre_position_recyclerview);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.addItemDecoration(CommItemDecoration.createVertical(Color.TRANSPARENT, DimenUtil.dp2px(context, 2)));
        recyclerView.addItemDecoration(CommItemDecoration.createHorizontal(Color.TRANSPARENT, DimenUtil.dp2px(context, 2)));
        ((DefaultItemAnimator) Objects.requireNonNull(recyclerView.getItemAnimator())).setSupportsChangeAnimations(false);
        adapter = new PrePositionFragmentAdapter(context, this);
        recyclerView.setAdapter(adapter);
        setListener();
    }

    private void setListener() {
        delImage.setOnClickListener(v -> del());
        delCancel.setOnClickListener(v -> cancel());
        delSubmit.setOnClickListener(v -> submit());
        guardImage.setOnClickListener(v -> guard());
        ptzReset.setOnClickListener(v -> showPTZOptimization());
    }

    private void showPTZOptimization(){
        if (context instanceof CameraViewActivity) {
            CameraViewActivity activity = (CameraViewActivity) context;
            activity.showPTZOptimization();
        }
    }

    private void guard(){
        int pos = adapter.getSelectPosition();
        if (pos == -1){
            TGToast.showToast(R.string.txt_select_guard_tip);
        }else {
            showGuardDialog();
        }
    }

    protected void submit() {
        if (!camera.isConnected()){
            TGToast.showToast(R.string.camera_send_failed);
            return;
        }
        CameraHelper.deletedPresetPoints(camera, pspType, adapter.getSelectedPresetPoints());
    }

    private void cancel() {
        delImage.setVisibility(View.VISIBLE);
        setPTZResetShow(isSupportPTZReset);
        showGuardImageButton();
        setDelCancel();
    }

    private void del() {
        if (adapter.getPrePositions().size() == 0) return;
        delCancel.setVisibility(View.VISIBLE);
        delImage.setVisibility(View.GONE);
        guardImage.setVisibility(View.GONE);
        setPTZResetShow(false);
        adapter.setEditEnable(true);
        adapter.clearSelectedPresetPoints();
    }

    public void setCamera(@NonNull Camera camera) {
        this.camera = camera;
        adapter.setData(camera.uid);
        adapter.setCamera(camera);
        if (camera.isConnected()){
            CameraHelper.getPspCMD(camera);
        }
    }

    @Override
    public void click(int position) {
        if (camera != null && camera.isConnected()){
            createDialog(position + 1);
        }else {
            TGToast.showToast(R.string.camera_send_failed);
        }
    }

    @Override
    public void updateDelStatus() {
        if (adapter.isEditEnable()) {
            delCancel.setVisibility(View.VISIBLE);
            if (adapter.getSelectedPresetPoints().size() > 0) {
                delSubmit.setVisibility(View.VISIBLE);
            } else {
                delSubmit.setVisibility(View.GONE);
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private void createDialog(int position) {
        CameraHelper.getPtzPosCMD(camera);
        PrePositionCreateDialog dialog = new PrePositionCreateDialog(context).builder(adapter.getMode());
        String c = LanguageUtils.getLanguage(context);
        String name = context.getResources().getString(R.string.message_play_address) + position;
        if (!StringUtils.isEmpty(c) && c.equals(LanguageUtils.ZH_CN)) {
            name = String.valueOf(position);
        }

        dialog.setEditText(name);
        if (context instanceof CameraViewActivity) {
            CameraViewActivity activity = (CameraViewActivity) context;
            bitmap = activity.getPlayerView().getTextureViewBmp();
            if (bitmap != null) {
                dialog.setImageBitmap(bitmap);
            }
        }
        dialog.setListener(text -> {
            if(camera != null && camera.isConnected()){
                DevicePresetPoints prePosition = new DevicePresetPoints();
                prePosition.name = text;
                prePosition.pos = ptzPos;
                prePosition.num = position;
                if (ptzPos!=null){
                    prePosition.x = ptzPos.x;
                    prePosition.y = ptzPos.y;
                    prePosition.z = ptzPos.z;
                }
                prePosition.uuid = camera.uid;
                adapter.addData(prePosition);
                adapter.saveImage(ImageUtils.ImageCrop(bitmap, PrePositionAdapter.IMAGE_WIDTH, PrePositionAdapter.IMAGE_HEIGHT, false), prePosition);
                adapter.notifyDataSetChanged();
                CameraHelper.setPresetPoints(camera, pspType, prePosition);
                ObjectBoxUtil.saveDevicePresetPoints(adapter.getPrePositions(),camera.uid);
            }else {
                TGToast.showToast(R.string.camera_send_failed);
            }
        });

        dialog.show();
    }

}
